﻿// -----------------------------------------------------------------------
// <copyright file="WorkOrder_DAL.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace PMSGSC.DAL
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class WorkOrder_DAL:BaseDAL
    {

        public static List<WorkOrder> GetDataByEquipmentID(int id, int shipID, bool isChanged)
        {
            if (isChanged)
            {
                DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, DB.WorkOrders);
            }
            List<WorkOrder> workOrderList = DB.WorkOrders.Where(n => n.Equipment_ID == id && (n.Type == 1 || n.Type == 2) && n.Complete == false).ToList();
            List<WorkOrder> wList = DB.WorkOrders.Where(n => n.Type == 3 && n.Complete == false).ToList();
            for (int i = 0; i < wList.Count; i++)
            {
                if (!TestJobIsRound(id, wList[i].Round_ID.Value))
                {
                    wList.RemoveAt(i);
                    i--;
                }
            }
            workOrderList.AddRange(wList);
            return workOrderList;
        }
        public static int GetAmountOfWorkOrderDue(Department department)
        {
            int count = 0;
            foreach (Employee e in department.Employees)
            {
                count += DB.WorkOrders.Where(n => n.RespDescipline_ID == e.Employee_ID && n.Type != 4 && 
                    ((n.NextDue != null && n.NextDue.Value.AddDays(n.AlarmDaybefore.Value).Date.CompareTo( DateTime.Now.Date) <= 0) || (n.NextDue == null && n.TimeDone >= n.Frequency)) && n.Complete == false).Count();
            }
            return count;
        }
        public static List<WorkOrder> GetWorkOrderOrderDue(int departmentID)
        {
            Department department = DB.Departments.Where(n => n.Department_ID == departmentID).FirstOrDefault();

            List<WorkOrder> wList = new List<WorkOrder>();
            foreach (Employee e in department.Employees)
            {
                wList.AddRange(DB.WorkOrders.Where(n => n.RespDescipline_ID == e.Employee_ID && n.Type != 4 &&
                    ((n.NextDue != null && n.NextDue.Value.AddDays(n.AlarmDaybefore.Value).Date.CompareTo(DateTime.Now.Date) <= 0) || (n.NextDue == null && n.TimeDone >= n.Frequency)) && n.Complete == false).Cast<WorkOrder>().ToList());
            }

            return wList;
        }

        public static List<WorkOrder> GetWorkOrderOrderOverDue(int departmentID)
        {
            Department department = DB.Departments.Where(n => n.Department_ID == departmentID).FirstOrDefault();

            List<WorkOrder> wList = new List<WorkOrder>();
            foreach (Employee e in department.Employees)
            {
                wList.AddRange(DB.WorkOrders.Where(n => n.RespDescipline_ID == e.Employee_ID && n.Type != 4 &&
                    ((n.NextDue != null && n.NextDue.Value.AddDays(n.AlarmDaybefore.Value).Date.CompareTo(DateTime.Now.Date) > 0) || (n.NextDue == null && n.TimeDone > n.Frequency)) && n.Complete == false).Cast<WorkOrder>().ToList());
            }

            return wList;
        }


        public static void UpdateCounterOfJob(int equipID, int Value)
        {
            List<WorkOrder> workOrders = DB.WorkOrders.Where(n => n.Equipment_ID == equipID && n.Type == 1 && n.Complete == false).ToList();
            foreach (WorkOrder w in workOrders)
            {
                w.TimeDone += Value;
                Update(w);
            }
        }

        public static List<WorkOrder> WorkOrderHistory(int id, int shipID, bool isChanged)
        {
            if (isChanged)
            {
                DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, DB.WorkOrders);
            }
            List<WorkOrder> workOrderList = DB.WorkOrders.Where(n => n.Equipment_ID == id && (n.Type == 1 || n.Type == 2) && n.Complete == true).ToList();
            List<WorkOrder> wList = DB.WorkOrders.Where(n => n.Type == 3 && n.Complete == true).ToList();
            for (int i = 0; i < wList.Count; i++)
            {
                if (!TestJobIsRound(id, wList[i].Round_ID.Value))
                {
                    wList.RemoveAt(i);
                    i--;
                }
            }
            workOrderList.AddRange(wList);
            return workOrderList;
        }

        public static bool TestJobIsRound(int EquipID, int RoundID)
        {
            List<RoundJob> roundJobs = DB.RoundJobs.Where(n => n.Round_ID == RoundID).ToList();
            foreach (RoundJob rj in roundJobs)
            {
                if (rj.Job.Equipment_ID == EquipID)
                    return true;
            }
            return false;
           
        }
        public static List<WorkOrder> GetAll(int shipID)
        {
            return  DB.WorkOrders.Where(n => (n.Type != 4) && n.Complete == false).ToList();
        }
        public static bool UpdateRoundWorkOrder(int WorkOrderID, int roundID)
        {
            try
            {
                WorkOrder j = GetDataById(WorkOrderID);
                // j.Round = DB.Rounds.Single(n=>n.Round_ID == roundID);
                DB.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }
        // Lấy WorkOrder theo Id
        public static WorkOrder GetDataById(int id)
        {
            return DB.WorkOrders.Where(m => m.WorkOrder_ID == id).FirstOrDefault();
        }
        public static WorkOrder GetWorkOrderByJobID(int jobID)
        {
            return DB.WorkOrders.Where(n => n.Job_ID == jobID && n.Complete == false).FirstOrDefault();
        }
        //Thêm một WorkOrder
        public static bool Insert(WorkOrder WorkOrder)
        {
            try
            {
                DB.WorkOrders.InsertOnSubmit(WorkOrder);
                DB.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                string str = ex.ToString();
                return false;
            }

        }
        public static WorkOrder GetDataByName(string name, int shipID)
        {
            return DB.WorkOrders.Where(n => n.Title == name && n.Ship_ID == shipID).FirstOrDefault();
        }
     
        public static WorkOrder GetDataByNumber(string code)
        {
            return DB.WorkOrders.Where(n => n.WorkOrderNumber == code).FirstOrDefault();
        }
        public static WorkOrder GetLastWorkOrder()
        {
            List<WorkOrder> listWorkOrder = DB.WorkOrders.ToList();
            return listWorkOrder[listWorkOrder.Count - 1];
        }

        // Xóa một WorkOrder
        public static bool Delete(WorkOrder WorkOrder)
        {
            try
            {
                DB.WorkOrders.DeleteOnSubmit(WorkOrder);
                DB.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }
        public static bool TestBeforeDelete(WorkOrder WorkOrder)
        {
            PartWorkOrder jp = DB.PartWorkOrders.Where(n => n.WorkOrder_ID == WorkOrder.WorkOrder_ID).FirstOrDefault();
            if (jp != null)
                return false;
            RescheduleLog res = DB.RescheduleLogs.Where(n => n.WorkOrder_ID == WorkOrder.WorkOrder_ID).FirstOrDefault();
            if (res != null)
                return false;
            AttachmentWorkOrder attach = DB.AttachmentWorkOrders.Where(n => n.WorkOrder_ID == WorkOrder.WorkOrder_ID).FirstOrDefault();
            if (attach != null)
                return false;

            return true;
        }
        public static bool DeleteByID(int id)
        {
            try
            {
                WorkOrder j = GetDataById(id);
                DB.WorkOrders.DeleteOnSubmit(j);
                DB.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        // Cập nhật WorkOrder
        public static bool Update(WorkOrder WorkOrder)
        {
            try
            {
                WorkOrder objWorkOrder = GetDataById(WorkOrder.WorkOrder_ID);

                objWorkOrder.WorkOrderNumber = WorkOrder.WorkOrderNumber;
                objWorkOrder.JobDescription = WorkOrder.JobDescription;
                objWorkOrder.Equipment_ID = WorkOrder.Equipment_ID;
                objWorkOrder.Frequency = WorkOrder.Frequency;
                objWorkOrder.SC_ID = WorkOrder.SC_ID;
                objWorkOrder.Ship_ID = WorkOrder.Ship_ID;
                objWorkOrder.Job_ID = WorkOrder.Job_ID;

                objWorkOrder.CreateDate = WorkOrder.CreateDate;
                objWorkOrder.NextDue = WorkOrder.NextDue;
                objWorkOrder.TimeUnit = WorkOrder.TimeUnit;
                objWorkOrder.AlarmDaybefore = WorkOrder.AlarmDaybefore;

                objWorkOrder.TimeDone = WorkOrder.TimeDone;

                objWorkOrder.ActionTaken = WorkOrder.ActionTaken;
                objWorkOrder.Cause = WorkOrder.Cause;
                objWorkOrder.CreateDate = WorkOrder.CreateDate;
                objWorkOrder.Effect = WorkOrder.Effect;
                objWorkOrder.OverdueReason = WorkOrder.OverdueReason;
                objWorkOrder.StatusJob_ID = objWorkOrder.StatusJob_ID;
                objWorkOrder.Title = WorkOrder.Title;
                objWorkOrder.Type = WorkOrder.Type;

                objWorkOrder.EmployeeCreate = WorkOrder.EmployeeCreate;
                objWorkOrder.RespDescipline_ID = WorkOrder.RespDescipline_ID;

                DB.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }

        public static int GetQuantityWorkOrder(int shipID)
        {
            return DB.WorkOrders.Where(n => n.Ship_ID == shipID).Count() + 1;
        }
        public static bool IsExitsCodeWorkOrder(string workOrderNumber, int shipID)
        {
            WorkOrder objWorkOrder = null;
            objWorkOrder = DB.WorkOrders.Where(m => (m.WorkOrderNumber == workOrderNumber) && (m.Ship_ID == shipID)).FirstOrDefault();
            return objWorkOrder == null ? true : false;
        }

        public static bool IsExitsTitleWorkOrder(string Title, int shipID)
        {
            WorkOrder objWorkOrder = null;
            objWorkOrder = DB.WorkOrders.Where(m => (m.Title == Title) && (m.Ship_ID == shipID)).FirstOrDefault();
            return objWorkOrder == null ? true : false;
        }
        public static List<WorkOrder> GetWork(string Number, string Title, int Component, int shipID)
        {
            DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, DB.WorkOrders);
            var query = "select * from WorkOrder";
            var queryTemp = "";
            if (Number != "")
            {
                queryTemp += "WorkOrderNumber= '" + Number + "' ";
            }
            if (Title != "")
            {
                if (queryTemp.ToString() != "")
                {
                    queryTemp += "and ";
                }
                queryTemp += "Title= N'" + Title + "' ";
            }
            if (Component != 0)
            {
                if (queryTemp.ToString() != "")
                {
                    queryTemp += "and ";
                }
                queryTemp += "Equipment_ID = '" + Component + "' ";
            }
            if (queryTemp == "")
            {
                return BaseDAL.DB.ExecuteQuery<WorkOrder>(query).ToList().Where(n => n.Ship_ID == shipID && n.NextDue != null && n.Complete == false && n.Type != 4).ToList();
            }
            else
            {
                query += " where ";
                query += queryTemp;
                return BaseDAL.DB.ExecuteQuery<WorkOrder>(query).ToList().Where(n => n.Ship_ID == shipID && n.NextDue != null && n.Complete == false && n.Type != 4).ToList();
            }
        }

    }
}
